//
//  UserManger.swift
//  DKE-Album
//
//  Created by 杨东宝 on 2020/5/18.
//  Copyright © 2020 杨东宝. All rights reserved.
//

import UIKit

public enum UserLoginType {
    
    case  kUserLoginTypeUnKnow //未知
    case  kUserLoginTypeWeChat     //微信登录
    case  kUserLoginTypeQQ         //QQ登录
    case  kUserLoginTypePwd(_ dict:[String:Any])        //账号密码
    case  kUserLoginTypeCode(_ dict:[String:Any])        //账号验证码
    
}

public enum ksmsType {
    
    case  ksmsTypeLogin //注册登录
    case  ksmsTypeChangePWD     //修改密码
    case  ksmsTypeLoginBindPhone        //绑定手机号
    case  ksmsTypeLoginThirsBindPhone        //第三方登录绑定手机号
    
    
}


//MARK:-用户信息存储
//用户信息缓存 名称
let KUserCacheName  = "KUserCacheName"
//用户model缓存
let KUserModelCache  = "KUserModelCache"

let KDeviceArrayCache  = "KDeviceArrayCache"

//MARK:-拼写错词次数记录
let KFailWordCount  = "KFailWordCount"
let KFailWordDic  = "KFailWordDic"

//用户管理者
let  userManger = UserManger.sharedInstance

//是否登录
let  isLogin = UserManger.sharedInstance.isLogined

typealias SucessOrErrowBlock = (Bool,String?) ->Void

class UserManger: NSObject {
    //登录回调
    var loginBlock:SucessOrErrowBlock?
    //记录当前登录状态
    var _isLogined:Bool = false
    //当前用户token
    var token:String?
    //记录当前登录类型
    var loginType:UserLoginType?
    //记录当前用户信息
    var curUserInfo:UserInfo?
    // 创建单例
    static let sharedInstance = UserManger()
    // 设置初始化方法为私有，防止报错
    private override init() {
        
    }
    var isLogined:Bool{
        set{
            _isLogined = newValue
        }
        get{
            if !_isLogined {
                appManger.PresentToLoginVC()
            }
            return _isLogined
        }
        
    }
    
    //MARK:- ————— 获取验证码 —————
    // 参数:手机,验证码，新密码
    func getCode(phone:String,type:ksmsType, completion:@escaping SucessOrErrowBlock) {
 
        var api:UserClassAPI?
        switch type {
        case .ksmsTypeLogin:
            api = UserClassAPI.getCodeToServer(phone)
        case .ksmsTypeChangePWD:
            api = UserClassAPI.getCodeTochangePssword(phone)
        case .ksmsTypeLoginBindPhone:
            api = UserClassAPI.getCodeToBindPhone(phone)
        case .ksmsTypeLoginThirsBindPhone:
            api = UserClassAPI.getCodeToBindThirdPhone(phone)
        }
        NetWorkRequest(api!, completion: { (object) in
            completion(true,nil)
            
        }, failed: { (message) in
            
            completion(false,message)
            
        }, errorResult: nil)
    }    
    //MARK:- ————— 修改密码 —————
    // 参数:手机,验证码，新密码
    func changePassword(parame:[String:Any], completion:@escaping SucessOrErrowBlock) {
        YDBProgressHUD.showLoading("正在修改，请稍候")
        NetWorkRequest(UserClassAPI.changePassword(parame), completion: { (object) in
            YDBProgressHUD.dismissHUD()
            completion(true,nil)
        }, failed: { (message) in
            YDBProgressHUD.dismissHUD()
            completion(false,message)
            YDBProgressHUD.showError(message)
        }, errorResult: nil)
    }
    
    
    //MARK:- ————— 绑定手机号 带密码 —————
    // 参数:手机
    func bindPhonePass(parame:[String:Any], completion:@escaping SucessOrErrowBlock) {
        YDBProgressHUD.showLoading("正在修改，请稍候")
        NetWorkRequest(UserClassAPI.bandingPhoneToServer(parame), completion: { [weak self] (object) in
            YDBProgressHUD.dismissHUD()
            self?.getUserInfor(completion: completion)
            completion(true,nil)
            }, failed: { (message) in
                YDBProgressHUD.dismissHUD()
                completion(false,message)
                YDBProgressHUD.showError(message)
        }, errorResult: nil)
    }
    
    //MARK:- ————— 修改绑定手机号 —————
    // 参数:手机
    func bindPhons(parame:[String:Any], completion:@escaping SucessOrErrowBlock) {
        YDBProgressHUD.showLoading("正在修改，请稍候")
        NetWorkRequest(UserClassAPI.bandingPhone(parame), completion: { [weak self] (object) in
            YDBProgressHUD.dismissHUD()
            self?.getUserInfor(completion: completion)
            completion(true,nil)
            }, failed: { (message) in
                YDBProgressHUD.dismissHUD()
                completion(false,message)
                YDBProgressHUD.showError(message)
        }, errorResult: nil)
    }

    //MARK:- ————— 手机号登录 —————
    // 参数:手机 ,验证码，密码登录
    private  func phoneLogin(loginType:UserLoginType, completion:@escaping SucessOrErrowBlock) {
        
        var loginAPI:UserClassAPI?
        
        switch loginType {
        case let .kUserLoginTypePwd(param):
            loginAPI = .loginToServerPwd(param);
        case let .kUserLoginTypeCode(param):
            loginAPI = .loginToServerCode(param);
        default:return
        }
        
        YDBProgressHUD.showLoading("正在登录，请稍候")
        NetWorkRequest(loginAPI!, isHideFailAlert: false, modelType: UserInfo.self,pageType: PageInfor.self, successCallback: { [weak self] (model,page, message, str) in
            self?.curUserInfo = model as? UserInfo
            self?.getUserInfor(completion: completion)
            
        }) { (code, msg) in
            completion(false,msg)
        }
    }
    
    //MARK:- ————— 获取用户信息 —————
    // 参数:手机 ,验证码，密码登录
    func getUserInfor(completion:@escaping SucessOrErrowBlock){
        
        NetWorkRequest(UserClassAPI.loadUserInfor, isHideFailAlert: false, modelType: UserInfo.self,pageType: PageInfor.self, successCallback: { [weak self] (model,page, message, str) in
            self?.curUserInfo = model as? UserInfo
            self?.saveUserInfor()
            completion(true,message)
        }) { (code, msg) in
            completion(false,msg)
        }
    }

    //MARK:- ————— 退出登录 —————
    func loginOut(completion:@escaping SucessOrErrowBlock){
        
        self.curUserInfo = nil;
        self.isLogined = false;

        
        guard let cache = YYCache.init(name: KUserCacheName) else {return}
        cache.removeAllObjects {
            completion(true,nil)
        }
        appManger.jumpToLoginVC()
    }
    //MARK:- ————— 储存用户信息到本地 —————
    func saveUserInfor(){
        if  self.curUserInfo != nil {
            let cache = YYCache.init(name: KUserCacheName)
            let dict = self.curUserInfo!.kj.JSONObject()
            self.isLogined = true
            cache?.setObject(dict as NSCoding, forKey: KUserModelCache)
            NotificationCenter.default.post(name: loginSuc, object: ["index": index])
        }
    }
    //MARK:————— 加载本地用户信息 —————
    func loadUserInfor(){
        guard let cache = YYCache.init(name: KUserCacheName) else {return}
        guard let userDic: [String:Any] = cache.object(forKey: KUserModelCache) as? [String : Any]  else {
            DebugLog("解析失败")
            return}
        self.curUserInfo = userDic.kj.model(UserInfo.self)
        self.isLogined = true
        self.token = self.curUserInfo?.token;
    }
}

extension  UserManger{

    //MARK:- —————存储错词记录 —————
    func saveWorongWord(dict:[String:Any]){
        if  self.curUserInfo != nil {
            let cache = YYCache.init(name: KFailWordCount)
            cache?.setObject(dict as NSCoding, forKey: KFailWordDic)
        }
    }
    //MARK:————— 加载错词 —————
    func loadWordWord() -> [String:Any]?{
        guard let cache = YYCache.init(name: KFailWordCount) else {return nil}
        guard let userDic: [String:Any] = cache.object(forKey: KFailWordDic) as? [String : Any]  else {
            return nil}
        return userDic
    }
    
}
extension UserManger{
    
    func addDeviceModel(deviceModel:DeviceModel){
        
        guard let cache = YYCache.init(name: KUserCacheName) else {return}
        
        var devArray: [Dictionary]? = cache.object(forKey: KDeviceArrayCache) as? [Dictionary<String, Any>]

        var have = false
        
        if devArray != nil{
            for device in devArray! {
                let model:DeviceModel =  device.kj.model(type: DeviceModel.self) as! DeviceModel
                if model.ID == deviceModel.ID{
                    have = true
                    break
                }
            }
        }else{
            devArray = [Dictionary]()
        }

//        if !have{
            let dict = deviceModel.kj.JSONObject()
            devArray?.append(dict)
            cache.setObject(devArray! as any NSCoding as NSCoding, forKey: KDeviceArrayCache)
//        }
    }
    func getDeviceList(isWifi:Bool? = false) -> [DeviceModel]?{
        guard let cache = YYCache.init(name: KUserCacheName) else {return nil}
        guard let devArray: [Dictionary] = cache.object(forKey: KDeviceArrayCache) as? [Dictionary<String, Any>]  else {
            DebugLog("解析失败")
            return nil
        }

        let deviceArray = devArray.kj.modelArray(type: DeviceModel.self) as! [DeviceModel]
        
        var listArray = [DeviceModel]()
        
        for device1:DeviceModel in deviceArray {
            if device1.isWifi == isWifi{
                listArray.append(device1)
            }
        }
        return listArray;
    }
}
